package com.bishe.shiro;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 整合Shiro框架的配置类
 *
 * @author passerbyYSQ
 * @create 2020-08-20 23:10
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        Map<String,String> map = new LinkedHashMap<>();
        //登陆认证拦截：未登录会跳转登陆页面
        map.put("/user/login","anon");
        map.put("/user/logout","anon");
        map.put("/doc.html", "anon");
        map.put("/swagger-resources/**", "anon");
        map.put("/v2/api-docs", "anon");
        map.put("/v2/api-docs-ext", "anon");
        map.put("/webjars/**", "anon");

        map.put("/**","anon");
        bean.setFilterChainDefinitionMap(map);

        return bean;
    }

    //DefaultWebSecurityManager （第二步：管理realm对象）
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;

    }

    //创建realm对象，需要自定义类 (第一步:创建realm对象)
    @Bean(name="userRealm")  //@Bean注解后便被spring托管,不加name属性，默认name值为方法名,这里就加一下吧
    public UserRealm userRealm(){
        return new UserRealm();
    }

}
